<template>
  <a-drawer
    placement="right"
    title="填写设备联动下发命令"
    :width="1000"
    @close="close"
    :visible="visible"
    :bodyStyle="{paddingBottom: '80px'}"
  >
    <a-form :form="form" layout="vertical">
      <a-row :gutter="16">
        <a-col :span="6">
          <a-form-item label="选择需要下发的命令">
            <a-select v-decorator="field('commandId','命令',true,command.id)"
                      @change="handleSelectedCommandChange">
              <a-select-option v-for="c in commands"
                               :key="c.id"
                               :value="c.id">
                <span style="color: #606266;">{{c.name}}</span>
                <span style="margin-left: 10px; color: #909399;">{{c.reqCode}}</span>
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item label="数据下发有效期">
            <a-input-number v-decorator="field('validTime','数据下发有效期',true,60)"
                            style="width: 100%;"
                            :min="0"
                            :max="604800"
                            :formatter="value => `${value}秒`"
                            :parser="value => value.replace('秒', '')"/>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item label="是否必须回复">
            <a-radio-group v-decorator="field('isecho','是否必须回复',true,true)">
              <a-radio :value="true">是</a-radio>
              <a-radio :value="false">否</a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
        <a-col :span="6"
               v-for="param in commandParams"
               :key="param.id">
          <a-form-item
            :label="param.cnName || param.name"
            :required="false"
          >
            <a-input
              v-decorator="[
                    `reqData[${param.name}]`,
                    {
                      validateTrigger: ['change', 'blur'],
                      rules: [
                        {
                          required: false,
                          whitespace: true,
                        },
                      ],
                    },
                  ]"
              :placeholder="param.cnName"
            />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <div
      :style="{
          position: 'absolute',
          right: 0,
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e9e9e9',
          padding: '10px 16px',
          background: '#fff',
          textAlign: 'right',
          zIndex: 1,
        }"
    >
      <a-button :style="{marginRight: '8px'}" @click="close">
        取消
      </a-button>
      <a-button @click="handleSubmit" type="primary">确定</a-button>
    </div>
  </a-drawer>
</template>

<script>

  import {groupBy} from 'lodash'
  import {field} from '@/utils/util'
  import {findProductCommands} from "@/api/product"
  import {findCommandParams} from "@/api/command"

  export default {

    data() {
      return {
        visible: false,
        form: this.$form.createForm(this),
        commands: [],// 命令
        command: {}, //当前选中的命令
        commandParams: [],  // 当前选中的命令对应的参数
        commandParamsCache: new Map(), // 命令参数缓存 key: command.id, value: req params
      }
    },

    props: {},

    computed: {
      // commandParams() {
      //   console.log('commandParams...')
      //   if (this.command && this.command.id) {
      //     return this.commandParamsCache.get(this.command.id)
      //   }else{
      //     return []
      //   }
      // }
    },

    created() {

    },

    mounted() {

    },

    methods: {
      field,

      open(productId) {
        this.visible = true
        this.productId = productId
        findProductCommands(productId).then(resp => {
          this.commands = resp.result.list
          if (this.commands && this.commands[0] && this.commands[0].id) {
            this.handleSelectedCommandChange(this.commands[0].id)
          }
        })
      },

      close() {
        this.visible = false
      },

      clearForm(){
        this.form.resetFields()
        this.commands = []
        this.command = {}
        this.commandParams = []
        this.commandParamsCache = new Map()
      },


      handleSelectedCommandChange(commandId) {
        if (commandId) {
          this.command = this.commands.find(c => c.id === commandId)
          // 维护缓存
          if (this.commandParamsCache.has(commandId)) {
            this.commandParams = this.commandParamsCache.get(commandId)
          }else{
            findCommandParams(commandId).then(resp => {
              const paramMap = groupBy(resp.result.list, 'reqOrResp')
              this.commandParams = paramMap[true]
              this.commandParamsCache.set(commandId, paramMap[true])
            })

          }
        } else {
          this.command = {}
        }
      },

      handleSubmit() {
        this.form.validateFields((err, values) => {
          if (!err) {
            let cmd = Object.assign({},this.command)
            cmd.validTime = values.validTime
            cmd.isecho = values.isecho
            cmd.reqData = values.reqData || {}
            Object.keys(cmd.reqData).forEach(key=>{
              if(cmd.reqData[key]===undefined){
                delete cmd.reqData[key]
              }
            })
            this.close()
            this.$emit('success', cmd)
          }
        })
      }

    }

  }
</script>

<style lang="less" scoped>
  .req-param-box {
    height: 200px;
    border: 1px solid rgb(217, 217, 217);
    border-radius: 4px;
  }
</style>
